Page({
  data: {
    phone: '',
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  },
  
  onPhoneInput(e) {
    this.setData({ phone: e.detail.value });
  },
  
  onOldPasswordInput(e) {
    this.setData({ oldPassword: e.detail.value });
  },
  
  onNewPasswordInput(e) {
    this.setData({ newPassword: e.detail.value });
  },
  
  onConfirmPasswordInput(e) {
    this.setData({ confirmPassword: e.detail.value });
  },
  
  submitPasswordChange() {
    const { phone, oldPassword, newPassword, confirmPassword } = this.data;
    
    // 校验手机号格式
    const phoneReg = /^1[2-9]\d{9}$/;
    if (!phoneReg.test(phone)) {
      wx.showToast({ title: '手机号格式错误', icon: 'none' });
      return;
    }
    
    // 校验密码长度
    if (newPassword.length < 6) {
      wx.showToast({ title: '新密码长度至少6位', icon: 'none' });
      return;
    }
    
    // 校验密码一致性
    if (newPassword !== confirmPassword) {
      wx.showToast({ title: '两次密码不一致', icon: 'none' });
      return;
    }
    
    // 显示加载状态
    wx.showLoading({
      title: '正在修改密码...',
      mask: true
    });
    
    console.log('【修改密码】请求参数:', { phone, oldPassword, newPassword });
    
    wx.request({
      url: 'http://localhost:8080/api/userYZ/changePassword',
      method: 'POST',
      data: { phone, oldPassword, newPassword },
      success: (res) => {
        console.log('【修改密码响应】', res);
        
        if (res.statusCode === 200) {
          if (res.data && res.data.code === 200) {
            wx.showToast({ title: '修改成功' });
            setTimeout(() => {
              wx.removeStorageSync('userInfo');
              wx.redirectTo({ url: '/pages/denglu/denglu' });
            },1500);
          } else {
            wx.showToast({ 
              title: res.data.msg || '操作失败', 
              icon: 'none' 
            });
          }
        } else if (res.statusCode === 500) {
          wx.showModal({
            title: '服务器错误',
            content: '修改密码时服务器发生错误，请稍后重试',
            showCancel: false
          });
        } else {
          wx.showToast({ 
            title: `错误 ${res.statusCode}`, 
            icon: 'none' 
          });
        }
      },
      fail: (err) => {
        console.error('【请求失败】', err);
        wx.showToast({ 
          title: '网络连接失败，请检查网络设置', 
          icon: 'none' 
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  }
});